﻿--[[
    @brief      Red dot helper.
    @author     amadeuysu
    @verstion   1.0
    @date       2021-01-07
]]

RedDotHelper = 
{
    red_dots = {};
    base_key_name = "app.red_dot.";

    -- 在tpf父控件中加红点，红点是否显示由key_name标识的配置控制
    -- 父控件支持container和button
    -- 支持custom_layout，传递自定义元素，取代默认的红点
    AddRedDot = function(parent_cid, key_name, custom_layout)
        if RedDotHelper.ShouldShowRedDot(key_name) then
            local path = "common\\red_dot.tpf/TenioUILayout/UIObject/Children/UIObject?CtnRedDot";
            if nil ~= custom_layout and "" ~= custom_layout then
                path = custom_layout;
            end
            local dot_cid = layout_mgr.restore_sub_layout(parent_cid, path);
            if dot_cid == 0 then
                base_utility.log("AddRedDot failed:" .. key_name);
                return;
            end
            RedDotHelper.ShowRedDot(dot_cid, true);
            RedDotHelper.red_dots[dot_cid] = key_name;
        end
    end;

    -- 取消key_name控制的红点
    ClearRedDot = function(key_name)
        for cid, key in pairs(RedDotHelper.red_dots) do
            if key_name == key then
                RedDotHelper.SetRedDotShowed(key_name);
                RedDotHelper.ShowRedDot(cid, false);
            end
        end
    end;

    ShowRedDot = function(id, show)
        local ptr = ui_utility.get_ctrl_ptr_by_id(id);
        if nill == ptr then
            return;
        end
        if show then
            ui_utility.setproperty_by_id(id, "Visible", "true"); 
        else
            ui_utility.setproperty_by_id(id, "Visible", "false"); 
        end
    end;

    SetRedDotShowed = function(key_name)
        local data = {};
        data["common"] = 0;
        data["key"] = RedDotHelper.base_key_name .. key_name;
        data["value"] = 1;
        comm_center.call_service("Svr_SetConfig", data);
    end;

    ShouldShowRedDot = function(key_name)
        local info = {common = 0, key = RedDotHelper.base_key_name .. key_name};
        local config = comm_center.call_service("Svr_GetConfig", info);
        if nil ~= config and 1 == config.exits then
            local cfg_tbl = base_utility.json_to_table(config.value or "{}");
            if config.value == 1 or config.value == "1" then
                return false;
            end
        end
        return true;
    end;
};